<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 200px;" placeholder="请输入用户ID"/> -->
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入收货人名称"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <!-- <el-table-column align="center" width="100px" label="地址ID" prop="id" sortable/> -->

      <!-- <el-table-column align="center" min-width="100px" label="用户ID" prop="userId"/> -->

      <!-- <el-table-column align="center" min-width="100px" label="部门ID" prop="shopId"/> -->

      <el-table-column align="center" min-width="100px" label="收货人名称" prop="name"/>

      <el-table-column align="center" min-width="100px" label="手机号码" prop="tel"/>

      <el-table-column align="center" min-width="300px" label="区域地址">
        <template slot-scope="scope">
          {{ scope.row.province + scope.row.city + scope.row.county }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="300px" label="详细地址" prop="addressDetail"/>

      <!-- <el-table-column align="center" min-width="80px" label="默认" prop="isDefault">
        <template slot-scope="scope">
          {{ scope.row.isDefault ? '是' : '否' }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  <!-- 添加或修改对话框 -->
    <el-dialog class="addressDialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px" style="width: 580px; margin-left:50px;">
         <el-form-item label="联系人" prop="name">
          <el-input v-model="dataForm.name" maxlength="50" />
        </el-form-item>
          <el-form-item label="联系人手机" prop="tel">
          <el-input v-model="dataForm.tel" maxlength="50" />
        </el-form-item>

        <el-form-item label="区域地址" prop="city">
            <el-select @change="queryCity(dataForm.province)" v-model="dataForm.province" clearable placeholder="请选择" style="width: 150px;float:left;">
              <el-option
                v-for="item in province"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>

            <el-select v-if="dataForm.province" @change="queryCounty(dataForm.city)" v-model="dataForm.city" clearable placeholder="请选择" style="width: 150px;margin-left:10px;float:left;">
              <el-option
                v-for="item in city"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          
            <el-select v-if="dataForm.city" v-model="dataForm.county" clearable placeholder="请选择" style="width: 150px;margin-left:10px;float:left;">
              <el-option
                v-for="item in county"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
        </el-form-item>

     <el-form-item label="详细地址" prop="addressDetail">
          <el-input v-model="dataForm.addressDetail" maxlength="50" />
        </el-form-item>
   
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.addressDialog .el-dialog{
  width: 720px;
}
</style>
<script>
import { listAddress ,listRegion ,addAddress,updateAddress,deleteAddress } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'UserAddress',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      dialogFormVisible:false,
      listLoading: true,
      dialogStatus:'',
      options:[],
      province:[],
      city:[],
      county:[],
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        userId: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      rules: {
        name: [{ required: true, message: '联系人不能为空', trigger: 'blur' },{pattern:/^([a-zA-Z\u4e00-\u9fa5\·]{1,10})$/,message:'联系人姓名格式错误,请输入英文或汉字'}],
        tel: [{ required: true, message: '联系人手机不能为空', trigger: 'blur' },{pattern:/^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '请输入有效的手机号码'}],
        city: [{ required: true, message: '区域地址不能为空', trigger: 'blur' }],
        addressDetail: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
      },
      dataForm: {
        name: undefined,
        tel:undefined,
        province: undefined,
        county: undefined,
        city: undefined,
        addressDetail:undefined,
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 绑定enter事件
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  methods: {
    enterKey(event) {
      if(event.key=='Enter'){
        this.handleFilter()
      }
    },
    enterKeyupDestroyed() {
        document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() {
        document.addEventListener("keyup", this.enterKey);
    },
    getList() {
      this.listLoading = true
      listAddress(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    resetForm() {
      this.dataForm = {
         name: '',
        tel:'',
        province: '',
        county: '',
        city: '',
        addressDetail:'',
      }
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resetForm()
      this.queryProvince(0)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.queryAddress()

      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    queryAddress(){
       let data = {}
      data.parentId=0
      listRegion(data).then(response => {
        this.province=response.data.data.list
        this.province.forEach(element => {
        if(element.name==this.dataForm.province){
        data.parentId=element.id
        listRegion(data).then(response => {
        this.city=response.data.data.list
          this.city.forEach(element => {
            if(element.name==this.dataForm.city){
              data.parentId=element.id
              listRegion(data).then(response => {
              this.county=response.data.data.list
             })
            }
          });

      })
      }
      });
      })
    },
    queryProvince(parentId){
      let data = {}
      data.parentId=parentId
      listRegion(data).then(response => {
        this.province=response.data.data.list
      })
    },
    queryCity(province){
      let data = {}
      this.dataForm.city = ''
      this.province.forEach(element => {
        if(element.name==province){
        data.parentId=element.id
        listRegion(data).then(response => {
        this.city=response.data.data.list
      })
      }
      });
    },
    queryCounty(city){
      let data = {}
      this.dataForm.county = ''
      this.city.forEach(element => {
        if(element.name==city){
        data.parentId=element.id
        listRegion(data).then(response => {
        this.county=response.data.data.list
      })
      }
      });
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$confirm('此操作将添加地址, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
          addAddress(this.dataForm)
            .then(response => {
              this.dialogFormVisible = false
              this.$notify.success({
                title: '添加成功'
              })
              this.handleFilter()
            })
            .catch(response => {
              this.$notify.error({
                title: '添加失败',
                message: response.data.errmsg
              })
            })
            }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消添加'
          });          
        });
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$confirm('此操作将更新地址, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
          updateAddress(this.dataForm)
            .then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify.success({
                title: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '更新失败',
                message: response.data.errmsg
              })
            })
            }).catch(() => {
            this.$message({
            type: 'info',
            message: '已取消更新'
          }); 
          }); 
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除地址, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
      deleteAddress(row).then(() => {
        this.getList()
        this.$notify.success({
          title: '删除成功'
        })
      }).catch(response => {
        this.$notify.error({
          title: '删除失败',
          message: response.data.errmsg
        })
      })
      }).catch(() => {
      this.$message({
            type: 'info',
            message: '已取消更新'
          }); 
          }); 
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['地址ID', '用户ID', '收货人', '手机号', '省', '市', '区', '地址', '是否默认']
        const filterVal = ['id', 'userId', 'name', 'tel', 'province', 'city', 'county', 'addressDetail', 'isDefault']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '用户地址信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
